package com.inspur.icity.bus.api.user.service;

import com.inspur.icity.bus.api.user.model.*;
import com.inspur.icity.bus.api.user.repo.BusRouteDao;
import com.inspur.icity.bus.base.core.inspurresult.BusLocation;
import com.inspur.icity.bus.base.core.inspurresult.BusLocationResult;
import com.inspur.icity.bus.base.core.service.CrudService;
import com.inspur.icity.bus.base.core.util.DateUtil;
import com.inspur.icity.bus.base.core.util.GaodeMapApi;
import com.inspur.icity.bus.base.core.util.InspurApi;
import io.swagger.models.auth.In;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 线路Service
 */
@Service
public class BusRouteService extends CrudService<BusRouteDao, BusRoute, Integer> {

    @Autowired
    private BusSearchHistoryService busSearchHistoryService;

    @Autowired
    private BusRouteHistoryService busRouteHistoryService;

    @Autowired
    private BusSiteService busSiteService;

    @Autowired
    private BusBaseDataService busBaseDataService;

    /**
     * 获取线路详情
     * @param areacode 系统代码
     * @param routeName 线路名称
     * @param direction 描述
     * @param flag 标记是否需记录历史
     * @param mobile
     * @param longitude
     * @param latitude
     * @param isSave 是否记录搜索历史
     * @return
     */
    public Map<String,Object> getRouteDetails(String areacode, String routeName, String direction, Integer updown, String flag, String mobile, Double longitude, Double latitude, String isSave, Boolean isTnterval){
        Map lineDetailMap = new HashedMap();
        List<Map<String,Object>> siteList = new ArrayList<>();
        Map<String,Object> params = new HashedMap();
        params.put("areacode",areacode);
        params.put("routeName",routeName);
        params.put("direction",direction);
        params.put("updown",updown);

        //查询线路信息
        List<BusRoute> routes = find(params);
        if(null == routes || routes.size() <= 0){
            params.remove("updown"); //针对高德数据，环路
            routes = find(params);
        }
        if(null == routes || routes.size() <= 0){
            params.put("updown",updown);
            params.remove("direction"); //针对石家庄，不同跑法（历史数据）
            routes = find(params);
        }
        if(null == routes || routes.size() <= 0){
            return null;
        }
        BusRoute busroute = routes.get(0);
        lineDetailMap.put("startDirection",busroute.getBeginStationName());
        lineDetailMap.put("endDirection",busroute.getEndStationName());
        lineDetailMap.put("updown",busroute.getUpdown());
        lineDetailMap.put("lineName",busroute.getRouteName());
        lineDetailMap.put("lineId",busroute.getRouteId());
        lineDetailMap.put("firstOrder",busroute.getFirstOrder());// 首班时间
        lineDetailMap.put("lastOrder",busroute.getLastOrder());// 末班时间
        lineDetailMap.put("ticket",busroute.getTicket()); //票价


        Map<String,Object> map = new HashMap<>();
        map.put("code",areacode);
        List<BusBaseData> list = busBaseDataService.find(map);
        if(null == list || list.size() == 0){
            return null;
        }
        BusBaseData busBaseData = list.get(0);

        //查询BUS实时位置
        BusLocationResult busLocationResult = InspurApi.getBusLocation(busBaseData.getIcityUri(),areacode, String.valueOf(busroute.getRouteId()),String.valueOf(busroute.getUpdown()),"");
        lineDetailMap.put("carNo",getCarSum(busLocationResult));

        //查询站点信息，根据站点序号排序
        params.put("updown",updown);
        params.put("orderBy","order by stationIndex");
        List<BusSite> busSites = busSiteService.find(params);

        if(null == busSites || busSites.size() <= 0){
            params.remove("updown");
            busSites = busSiteService.find(params);
        }
        //封装站点
        Map stationMap = null;
        Integer siteId = getNear(busSites,longitude,latitude);//计算距离最近
        int index = 0;
        for(BusSite busSite :  busSites){
            stationMap = new HashedMap();
            stationMap.put("siteName",busSite.getStationName());
            stationMap.put("siteId",busSite.getStationIndex());
            if(null != siteId && siteId.equals(busSite.getId())){
                stationMap.put("isNear",true); //离我最近
            }else{
                stationMap.put("isNear",false);
            }
            stationMap.put("statue",getCarStatus(busSite.getStationIndex(),busLocationResult,index));
            siteList.add(stationMap);
            index++;
        }
        lineDetailMap.put("siteList",siteList);

        //保存当前用户搜索线路，排除济南城际公交
        if(null != flag && "search".equals(flag) && !isTnterval){
            busSearchHistoryService.saveSearchHistory(routeName,direction,updown,busroute.getRouteId(),1,mobile,areacode);
        }
        if(!"no".equals(isSave) && !isTnterval){ //排除济南城际公交、定时任务
            //保存当前用户常用路线
            BusRouteHistory history = new BusRouteHistory();
            history.setMobile(mobile);
            history.setName(routeName);
            history.setDirection(direction);
            history.setUpdown(updown);
            history.setAreacode(areacode);
            history.setCity("");
            history.setDeleted(0);
            history.setCreateTime(DateUtil.getSystemTime());
            busRouteHistoryService.add(history);
        }
        return lineDetailMap;
    }

    /**
     * 获取线路详情 -- 济南城际公交
     * @param areacode 系统代号
     * @param routeName 线路名称
     * @param direction 线路方向
     */
    public Map<String,Object> getRouteDetailsForJn(String areacode, String routeName, String direction, String flag, String mobile, Double longitude, Double latitude, String isSave, Boolean isTnterval){
        Map<String,Object> lineDetailMap = getRouteDetails(areacode,routeName,direction,null,flag,mobile,longitude,latitude, "no", isTnterval);
        return lineDetailMap;
    }

    /**
     * 剔除未出站的车辆 todo
     * @return
     */
    private Integer getCarSum(BusLocationResult busLocationResult){
        int i = 0;
        Integer siteIndex = 1;
        if(busLocationResult != null && "0000".equals(busLocationResult.getStatus()) && null != busLocationResult.getBusLocations()){
            for(BusLocation busLocation : busLocationResult.getBusLocations()){
                if(siteIndex.equals(busLocation.getStationIndex()) && "0".equals(busLocation.getArrive())){ //0表示到站，即在第一站
                    i = i+1;
                }
            }
            return busLocationResult.getBusLocations().size() - i;
        }else {
            return 0;
        }
    }

    /**
     * 获取距离登陆用户最近的站点--即获取两点间距离最短
     * @param busSites
     * @param longitude
     * @param latitude
     * @return
     */
    private Integer getNear(List<BusSite> busSites, Double longitude, Double latitude) {
        if(null == longitude || null == latitude){
            return null;
        }
        if(0 == longitude || 0 == latitude){
            return null;
        }
        double temp = 1000000;
        double distance;
        Integer siteId = null;
        for (BusSite busSite : busSites){
            distance = GaodeMapApi.getDistance(busSite.getLng(), busSite.getLat(),longitude,latitude);
            if(temp > distance){
                temp = distance;
                siteId = busSite.getId();
            }
        }
        return siteId;
    }

    /**
     * 页面显示--站点与车辆实时位置
     * @param siteId
     * @param busLocationResult
     * @return
     */
    public List<Integer> getCarStatus(Integer siteId,BusLocationResult busLocationResult,int index){
        List<Integer> carStatus = new ArrayList<>();
        //3普通站点  4车到站了  5 车在两站中间
        if(busLocationResult == null || !"0000".equals(busLocationResult.getStatus())){
            //没有车辆信息
            carStatus.add(3);
            return carStatus;
        }
        if(busLocationResult.getBusLocations() == null || busLocationResult.getBusLocations().size() == 0){
            carStatus.add(3);
            return carStatus;
        }
        for(BusLocation busLocation : busLocationResult.getBusLocations()){
            if(siteId.equals(busLocation.getStationIndex()) && "0".equals(busLocation.getArrive())){ //到站
                carStatus.add(4);
            }
            if(siteId.equals(busLocation.getStationIndex()) && "1".equals(busLocation.getArrive())){ //出站
                carStatus.add(5);
            }
        }
        if(carStatus.size() == 0){
            carStatus.add(3);
        }
        return carStatus;
    }


    /**
     * 查询线路信息（搜索框调用）
     * @param queryMap
     * @param result
     */
    public void queryBusRouter(Map<String, Object> queryMap, List<Map<String, Object>> result) {
        List<BusRoute> busroutes = find(queryMap);
        for (BusRoute busroute : busroutes){
            Map<String,Object> map = new HashedMap();
            map.put("type",1); //表示线路
            map.put("name",busroute.getRouteName());
            map.put("direction",busroute.getDirection());
            map.put("updown",busroute.getUpdown());
            result.add(map);
        }
    }

    /**
     * 批量保存
     * @param list
     */
    public void batchSave(List<BusRoute> list){
        curdRepo.batchSave(list);
    }

    /**
     * 根据参数获取库中线路个数
     * @param name
     * @param direction
     * @param areacode
     * @return
     */
    public int getRouteCount(String name, String direction, String areacode) {
        return curdRepo.getRouteCount(name,direction,areacode);
    }

    /**
     * 删除线路信息
     * @param codes
     */
    public void removeByAreacode(Set<String> codes) {
        curdRepo.removeByAreacode(codes);
    }

    /**
     * 删除线路信息
     * @param code
     */
    public void removeByAreacode(String code) {
        Set<String> codes = new HashSet<>();
        codes.add(code);
        curdRepo.removeByAreacode(codes);
    }

    /**
     * 删除线路数据
     * @param busRoutes
     */
    public void batchDelete(List<BusRoute> busRoutes) {
        for (BusRoute busRoute : busRoutes){
            curdRepo.removeByRouteId(busRoute.getRouteId(),busRoute.getAreacode());
        }
    }
}